package com.toweave.starter.utils;

import com.alibaba.fastjson2.JSON;

import java.util.List;
import java.util.Objects;

public class FastJsonUtil {
  // List 继承 Object List 与 Object 都可以时使用 ObjectToJsonString
  public static String ObjectToJsonString(Object object) {
    if (Objects.isNull(object)) {
      return "";
    }
    try {
      return JSON.toJSONString(object);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  public static <T> T JsonStringToList(String json, Class<T> clazz) {
    if (Objects.isNull(json)) {
      return null;
    }
    try {
      List<T> data = JSON.parseArray(json, clazz);
      return (T) data;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static <T> T JsonStringToObject(String json, Class<T> clazz) {
    if (Objects.isNull(json)) {
      return null;
    }
    try {
      T data = JSON.parseObject(json, clazz);
      return (T) data;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
